package com.qidian.mes.service.impl;

import com.qidian.mes.mapper.WorkOrderMapper;
import com.qidian.mes.pojo.WorkOrder;
import com.qidian.mes.service.WorkOrderService;
import com.qidian.mes.util.pojo.MESResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class WorkOrderServiceImpl implements WorkOrderService {
    @Autowired
    private WorkOrderMapper workOrderMapper;


    /**
     * 搜索
     *
     * @param workOrder
     * @return
     */
    @Override
    public MESResult list(WorkOrder workOrder) {
        List<WorkOrder> list = workOrderMapper.list(workOrder);
        return MESResult.ok(list);
    }

    /**
     * 获取所有数据
     *
     * @return
     */
    @Override
    public MESResult selectAll() {
        List<WorkOrder> list = selectByParentId(0L);
        return MESResult.ok(list);
    }

    @Override
    public MESResult getByWorkOrderId(Long workOrderId) {
        WorkOrder workOrder = null;
        if ((workOrder = workOrderMapper.selectByWorkOrderId(workOrderId)) != null) {
            return MESResult.ok(workOrder);
        }
        return MESResult.empty();
    }

    @Override
    public MESResult save(WorkOrder workOrder) {
        if (workOrderMapper.getByWorkOrderName(workOrder.getWorkOrderName()) != null) {
            return MESResult.duplicate();
        }
        if (workOrder.getParentId() != null) {
            workOrder.setAncestors("2");
        } else {
            workOrder.setAncestors("1");
            workOrder.setParentId(0L);
        }
        if (workOrderMapper.sava(workOrder) > 0) {
            return MESResult.ok();
        }
        return MESResult.fail();
    }

    @Override
    public MESResult update(WorkOrder workOrder) {
        WorkOrder workOrder1 = workOrderMapper.getByWorkOrderName(workOrder.getWorkOrderName());
        if (workOrder1 != null && workOrder1.getWorkOrderId() != workOrder.getWorkOrderId()){
            return MESResult.duplicate("工单名称重复");
        }
        if (workOrderMapper.update(workOrder) > 0) {
            return MESResult.ok();
        }
        return MESResult.fail();
    }

    @Override
    public MESResult delete(Long workOrderId) {
        if (workOrderMapper.delete(workOrderId) > 0) {
            return MESResult.ok();
        }
        return MESResult.fail();
    }

    /**
     * 递归遍历
     *
     * @param parentId
     * @return
     */
    private List<WorkOrder> selectByParentId(Long parentId) {
        List<WorkOrder> workOrders = workOrderMapper.selectByParentId(parentId);
        for (WorkOrder workOrder : workOrders) {
            if (workOrder.getAncestors().equals("1")) {
                workOrder.setChildren(selectByParentId(workOrder.getWorkOrderId()));
            }
        }
        return workOrders;
    }


}

